package handler

import (
	"context"
	"errors"
	pb "mpps/services/srv-UserLogin/proto"
	"mpps/tools/auth"
	common "mpps/tools/common"
	"mpps/tools/repository/dao"
	"mpps/tools/repository/dao/user"

	"github.com/asim/go-micro/v3/logger"
)

type UserLogin struct {
}

func NewUserLogin() *UserLogin {
	return &UserLogin{}
}

// Call is a single request handler called via client.Call or the generated client code
func (c *UserLogin) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
	if len(req.Email) <= 0 || len(req.Password) < 6 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if !common.IsEmail(req.Email) {
		return errors.New(common.ErrParamsValidation.Message)
	}
	query := user.User{
		Email:    req.Email,
		Password: req.Password,
	}

	query.UserId = common.Md5(query.Email)
	query.Password = common.Md5(query.Password)

	model := user.User{}
	result := dao.GetDB(ctx).
		Model(&user.User{}).
		Where("user_id = ? AND email = ? AND password = ?", query.UserId, query.Email, query.Password).
		Limit(1).
		Find(&model)
	if result.RowsAffected <= 0 {
		return errors.New(common.ErrPostLogin.Message)
	}
	// 生成token
	accessToken, refreshToken, err := auth.GenerateToken(model.UserId)
	if err != nil {
		logger.Info(err)
		return errors.New(common.ErrPostLogin.Message)
	}
	rsp.AccessToken = accessToken
	rsp.RefreshToken = refreshToken
	return nil
}
